﻿/*
 *  date: 2021-12-08
 *  author: Jn-chen
 *  cn: 事件管理器
 *  en: todo:
 */


using System.Collections.Generic;

namespace UBJ.EventKit
{
#if USEUBJFK
    public class EventManager : UBJ.CoreKit.ILife
#else
    public class EventManager
#endif
    {
        /// <summary>
        /// 单例
        /// </summary>
        public static EventManager Ins
        {
            get 
            {
                if (mIns == null) mIns = new EventManager();
                return mIns;
            }        
        }

        /// <summary>
        /// 获取一个事件控制器
        /// </summary>
        /// <param name="name"> 事件控制器名字 </param>
        /// <returns> 事件控制器对象 </returns>
        public EventController GetEventCtrl(string name)
        {
            for(int i = 0; i < mAllCtrls.Count; i++)
            {
                if (mAllCtrls[i].Name.Equals(name))
                {
                    return mAllCtrls[i];
                }
            }

            var newCtrl = new EventController(name);
            mAllCtrls.Add(newCtrl);
            return newCtrl;
        }

        /// <summary>
        /// 移除事件控制器
        /// </summary>
        /// <param name="name"> 事件控制器名字 </param>
        /// <returns> 移除是否成功 </returns>
        public bool RemoveEventCtrl(string name)
        {
            for (int i = 0; i < mAllCtrls.Count; i++)
            {
                if (mAllCtrls[i].Name.Equals(name))
                {
                    mAllCtrls.RemoveAt(i);
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="appName"> app名字 </param>
        public void Init(string appName)
        {

        }

        /// <summary>
        /// 帧更新
        /// </summary>
        /// <param name="deltaTime"> 单帧时间 </param>
        public void Update(float deltaTime)
        {

        }

        /// <summary>
        /// 离开游戏之前的操作
        /// </summary>
        public void ApplicationQuitBegin()
        {
            ClearAllEventCtrl();
        }

        /// <summary>
        /// 离开游戏之后的操作
        /// </summary>
        public void ApplicationQuitEnd()
        {
            mAllCtrls = null;
        }

        /// <summary>
        /// 清理所有EventCtrl
        /// </summary>
        private void ClearAllEventCtrl()
        {
            for(int i = 0; i < mAllCtrls.Count; i++)
            {
                mAllCtrls[i].Clear();
            }

            mAllCtrls.Clear();
        }


        private EventManager()
        {
            mAllCtrls = new List<EventController>();
        }

        private List<EventController> mAllCtrls;

        private static EventManager mIns;
    }
}
